package bmatch.tech.file.service.impl;

import bmatch.tech.file.model.MyDirectory;
import bmatch.tech.file.model.MyFile;
import bmatch.tech.file.model.Response;
import bmatch.tech.file.service.MyDirectoryService;
import bmatch.tech.file.util.DataStore;
import bmatch.tech.file.util.IDUtil;
import bmatch.tech.file.util.Query;

import java.util.Date;
import java.util.List;

/**
 * 文件夹服务实现
 *
 * @author: Awake
 * @date: 2018-12-02 12:52
 **/
public class MyDirectoryServiceImpl implements MyDirectoryService {
    @Override
    public Response create(String userId, String path, String name) {

        //查询出是否已经存在
        if (Query.queryDirectory(userId, path, name) != null) {
            return new Response(Response.RESPONSE_OK, "文件夹已经存在");
        }
        //添加一个文件夹
        MyDirectory directory = new MyDirectory();
        directory.setId(IDUtil.getUUID());
        directory.setGmtCreated(new Date());
        directory.setName(name);
        directory.setPath(path);
        DataStore.getDirectories().get(userId).add(directory);

        DataStore.storeDirectories();
        return new Response(Response.RESPONSE_OK, "文件夹创建成功");

    }

    @Override
    public Response delete(String userId, String path, String name) {
        //查询出文件夹是否存在
        if (Query.queryDirectory(userId, path, name) == null) {
            return new Response(Response.RESPONSE_OK, "文件夹不存在");
        }

        //按照所在路径列举所有文件夹 然后删除指定文件夹
        List<MyDirectory> myDirectories = Query.queryDirectoriesByUserId(userId);
        for (MyDirectory myDirectory : myDirectories) {
            if (myDirectory.getPath().equals(path) && myDirectory.getName().equals(name)) {
                myDirectories.remove(myDirectory);
                break;
            }
        }
        DataStore.storeDirectories();
        return new Response(Response.RESPONSE_OK, "文件夹删除成功");
    }

    @Override
    public Response rename(String userId, String path, String originalName, String targetName) {
        //查询出文件夹是否存在
        MyDirectory myDirectory = Query.queryDirectory(userId, path, originalName);
        if (myDirectory == null) {
            return new Response(Response.RESPONSE_OK, "文件夹不存在");
        } else {
            myDirectory.setName(targetName);
            DataStore.storeDirectories();
            return new Response(Response.RESPONSE_OK, "文件夹重命名成功");
        }

    }

    @Override
    public Response shift(String userId, String name, String originalPath, String targetPath) {
        //查询出文件夹是否存在
        MyDirectory myDirectory = Query.queryDirectory(userId, originalPath, name);
        if ( myDirectory== null) {
            return new Response(Response.RESPONSE_OK, "文件夹不存在");
        }else {
            //修改路径即可
            myDirectory.setPath(targetPath);
            DataStore.storeDirectories();
            return new Response(Response.RESPONSE_OK, "文件夹转移成功");
        }

    }
}
